package com.yulang.security.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.yulang.security.BaseResult;
import com.yulang.security.core.properties.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义失败处理器，响应json 或者 跳转页面
 */
@Component
public class CustomAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception)
            throws IOException, ServletException {
        if(securityProperties.getAuthentication().isResponseJson()){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(BaseResult.error(HttpStatus.UNAUTHORIZED.value(),exception.getMessage())));
            response.getWriter().flush();
        }else{
            Object toAuth = request.getAttribute("toAuth");
            if(toAuth!=null){
                super.setDefaultFailureUrl(securityProperties.getAuthentication().getLoginPage()+"?error");
                super.onAuthenticationFailure(request,response,exception);
            }else{
                String referer = request.getHeader("Referer");
                String before = StringUtils.substringBefore(referer, "?");
                super.setDefaultFailureUrl(before+"?error");
                super.onAuthenticationFailure(request,response,exception);
            }
        }
    }
}
